#include "obstacle.h"
#include <QRandomGenerator>

Obstacle::Obstacle(int speed, int lane, int type, QGraphicsItem *parent)
    : GameObject(parent), speed(speed), lane(lane), obstacleType(type),
    laneWidth(100), moveDirection(1)
{
    setupPixmap();

    int yPos = 300 - (lane * laneWidth) - pixmap().height() + 20;
    setPos(800, yPos);

    if(type == 2) { // 移动障碍物
        moveDirection = QRandomGenerator::global()->bounded(2) ? 1 : -1;
    }
}

void Obstacle::update()
{
    setPos(x() - speed, y());

    if(obstacleType == 2) { // 移动障碍物上下移动
        setPos(x(), y() + (moveDirection * 2));
        if(y() <= 100 || y() >= 300) {
            moveDirection *= -1;
        }
    }

    if(x() + pixmap().width() < 0) {
        scene()->removeItem(this);
        delete this;
        return;
    }
}

void Obstacle::setupPixmap()
{
    switch(obstacleType) {
    case 0: // 普通障碍
        setPixmap(QPixmap(":/image/D:/obstacle1.jpg").scaled(50, 50));
        break;
    case 1: // 高障碍
        setPixmap(QPixmap(":/image/D:/obstacle2.jpg").scaled(50, 80));
        break;
    case 2: // 移动障碍
        setPixmap(QPixmap(":/image/D:/obstacle3.jpg").scaled(50, 50));
        break;
    }
}
